package com.zhai.cloud.home.service;

import com.zhai.cloud.common.constant.LogConstant;
import com.zhai.cloud.common.util.JSONUtil;
import com.zhai.cloud.common.util.StringUtil;
import com.zhai.cloud.home.constant.HomeConstant;
import com.zhai.cloud.home.job.HomeJob;
import lombok.extern.slf4j.Slf4j;
import com.zhai.cloud.starter.quartz.service.QuartzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Created by 翟凤玺
 * @package com.zhai.cloud.home.service
 * @project-name zhai-cloud
 * @description 主页 定时任务 服务实现
 * @create-datetime 2019-8-6 14:21
 */
@Slf4j
@Service
public class HomeJobServiceImpl implements HomeJobService {

    private static final String BUSINESS_NAME = "【主页定时任务 服务】";
    private static final String METHOD_START = "（启动）";
    private static final String METHOD_STOP = "（暂停）";
    private static final String METHOD_CHANGE_CRON = "（变更定时任务表达式）";

    @Autowired
    QuartzService quartzService;

    @Override
    public void start(String jobCode, String cron, String state) {
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_START));
        /** 新增定时任务 */
        if (HomeConstant.JOB_STATE_START.equals(state)) {
            quartzService.addCronJob(HomeJob.class, jobCode, HomeConstant.JOB_GROUP_NAME_HOME, cron, null);
        }
        /** 重启定时任务 */
        if (HomeConstant.JOB_STATE_RESTART.equals(state)) {
            /** 变更定时任务 corn表达式 */
            quartzService.updateJob(jobCode, HomeConstant.JOB_GROUP_NAME_HOME, cron);

        }
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_START, LogConstant.RESULT, LogConstant.SUCCESS));
    }

    @Override
    public void stop(String jobCode) {
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_STOP, LogConstant.IN, JSONUtil.toStr(jobCode)));
        quartzService.pauseJob(jobCode, HomeConstant.JOB_GROUP_NAME_HOME);
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_STOP, LogConstant.RESULT, LogConstant.SUCCESS));
    }

    @Override
    public void changeCron(String jobCode, String cron) {
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_CHANGE_CRON));
        quartzService.updateJob(jobCode, HomeConstant.JOB_GROUP_NAME_HOME, cron);
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_CHANGE_CRON, LogConstant.RESULT, LogConstant.SUCCESS));
    }
}